﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilLibrary.FileTool
{
    public class FileFolderMonitor
    {
        private FileSystemWatcher _fileWatcher;

        public void StartMonitoring(string directoryPath)
        {
            // 创建 FileSystemWatcher 实例
            _fileWatcher = new FileSystemWatcher();

            // 设置要监视的目录路径
            _fileWatcher.Path = directoryPath;

            // 设置要监视的更改类型（例如：修改、创建、删除）
            _fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

            // 添加事件处理程序
            _fileWatcher.Changed += OnChanged;
            _fileWatcher.Created += OnChanged;
            _fileWatcher.Deleted += OnChanged;
            _fileWatcher.Renamed += OnRenamed;

            // 开启事件监听
            _fileWatcher.EnableRaisingEvents = true;

            Console.WriteLine($"已开始监视文件夹: {directoryPath}");
        }

        private void OnChanged(object source, FileSystemEventArgs e)
        {
            Console.WriteLine($"文件或文件夹发生变更: {e.FullPath}，事件类型: {e.ChangeType}");
        }

        private void OnRenamed(object source, RenamedEventArgs e)
        {
            Console.WriteLine($"文件或文件夹被重命名: 旧路径 {e.OldFullPath} -> 新路径 {e.FullPath}");
        }

        public void StopMonitoring()
        {
            if (_fileWatcher != null)
            {
                // 停止引发事件
                _fileWatcher.EnableRaisingEvents = false;

                // 清理资源
                _fileWatcher.Dispose();
                _fileWatcher = null;

                Console.WriteLine("已停止监视文件夹");
            }
        }

        /// <summary>
        /// 课外探索，弹出文件选择框
        /// </summary>
        //public static string SelectFolder(string description = "请选择一个文件夹：", Environment.SpecialFolder rootFolder = Environment.SpecialFolder.MyComputer)
        //{
        //    using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
        //    {
        //        folderDialog.Description = description;
        //        folderDialog.RootFolder = rootFolder;

        //        if (folderDialog.ShowDialog() == DialogResult.OK)
        //        {
        //            return folderDialog.SelectedPath;
        //        }
        //    }
        //    return string.Empty;
        //}
    }
}
